package com.garbuz.svnadmin.view
{
	import actionlib.common.query.conditions.nameIs;
	import actionlib.common.query.from;

	import com.garbuz.svnadmin.data.DataProviderBase;
	import com.garbuz.svnadmin.view.common.FilterBox;

	import mx.containers.Canvas;
	import mx.controls.listClasses.ListBase;
	import mx.events.FlexEvent;

	public class BrowseViewBase extends Canvas
	{
		[Bindable]
		public var dataGrid:ListBase;

		[Bindable]
		public var filterBox:FilterBox;

		private var _selectedName:String;
		private var _selectedIndex:int = -1;
		private var _firstRequest:Boolean = true;

		public function BrowseViewBase()
		{
			super();
			this.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete)
		}

		protected function onCreationComplete(event:FlexEvent):void
		{
			getDataProvider().busyEvent.addListener(handleBusy);
			getDataProvider().readyEvent.addListener(handleReady);
			onInitialize();
			retrieveData();
		}

		public function retrieveData():void
		{
			getDataProvider().retrieveData();
		}

		protected function getDataProvider():DataProviderBase
		{
			return null;
		}

		private function handleBusy():void
		{
			savePosition();
			enabled = false;
		}

		private function handleReady():void
		{
			enabled = true;

			if (filterBox)
			{
				filterBox.applyFilter();

				if (_firstRequest)
				{
					filterBox.setFocus();
					_firstRequest = false;
				}
			}

			restorePosition();
		}

		protected function onInitialize():void
		{
		}

		protected function savePosition(name:String = null):void
		{
			if (name)
			{
				_selectedName = name;
			}
			else
			{
				if (dataGrid.selectedItem)
				{
					_selectedName = dataGrid.selectedItem.name;
					_selectedIndex = dataGrid.selectedIndex;
				}
			}
		}

		protected function restorePosition():void
		{
			if (_selectedName)
			{
				dataGrid.selectedItem = from(dataGrid.dataProvider)
						.where(nameIs(_selectedName))
						.findFirst();
				dataGrid.validateNow();
			}

			if (!dataGrid.selectedItem
					&& _selectedIndex < dataGrid.rowCount
					&& _selectedIndex >= 0)
			{
				dataGrid.selectedIndex = _selectedIndex;
				dataGrid.validateNow();
			}

			if (dataGrid.selectedItem)
			{
				dataGrid.scrollToIndex(dataGrid.selectedIndex);
			}
			else
			{
				if (filterBox)
					filterBox.setFocus();
			}
		}
	}
}